<template>
  <canvas class="audio-visualizer" ref="canvasRef"></canvas>
</template>
<script>
import { mapState, mapGetters } from "vuex";

function drawVisualizer(analyser, visualizer) {
  requestAnimationFrame(() => drawVisualizer(analyser, visualizer));
  if (analyser == null) return;
  const bufferLength = analyser.frequencyBinCount;
  const dataArr = new Uint8Array(bufferLength);
  analyser.getByteFrequencyData(dataArr);
  const { width } = visualizer;
  const { height } = visualizer;

  const barWidth = width / bufferLength;

  const canvasCtx = visualizer.getContext("2d");
  canvasCtx.clearRect(0, 0, width, height);

  dataArr.forEach((item, index) => {
    const x = barWidth * index;
    const y = ((item / 255) * height) / 8;
    canvasCtx.fillStyle = `hsl(${(y / height) * 400}, 100%, 50%)`;
    canvasCtx.fillRect(x, height - y, barWidth, y);

    // const x = barWidth * index;
    // const y = item / 255 * width / 2;
    // canvasCtx.fillStyle = `hsl(${y / width * 400}, 100%, 50%)`;
    // canvasCtx.fillRect(x, width - y, barWidth, y);
  });
}
export default {
  name: "WebAudioVisualizer",
  data() {
    return {};
  },
  computed: {
    ...mapGetters(["analyser"]),
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      drawVisualizer(this.analyser, this.$refs.canvasRef);
    },
  },
};
</script>
<style lang="scss" scoped>
.audio-visualizer {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  pointer-events: none;
  z-index: 10;
}
</style>
